"""军队项目列表数据处理方法"""

from datetime import datetime
import webbrowser
import os


def analyze_tree(node, path, results, total):
    nuit_price = node.get("UnitPrice", 0)
    scale = node.get("Scale", 0)
    estimate = node.get("Estimate", 0)

    # 处理可能的空值和非数值类型
    try:
        calculated = round(float(nuit_price) * float(scale), 2)
        estimate = float(estimate)
    except:
        calculated = 0
        estimate = 0

    # 记录差异（允许 0.01 的误差）
    if abs(calculated - estimate) > 0.01:
        results.append({
            "path": path + [node["Name"]],
            "base_price": nuit_price,
            "scale": scale,
            "calculated": calculated,
            "estimate": estimate,
            "difference": round(abs(calculated - estimate), 2)
        })

    # 累加 Estimate
    total["sum"] += estimate

    # ========== 新增打印逻辑 ==========
    current_depth = len(path)
    indent = "│   " * current_depth  # 树形缩进符号
    branch = "├── " if current_depth > 0 else "┌── "

    # 打印当前节点信息
    print(f"{indent}{branch}当前节点: {node['Name']}")
    print(f"{indent}│   BasePrice: {nuit_price}")
    print(f"{indent}│   Scale:     {scale}")
    print(f"{indent}│   计算值:    {calculated:.2f}")
    print(f"{indent}└── Estimate:  {estimate}\n")

    # 递归处理子节点
    for child in node.get("children", []):
        analyze_tree(child, path + [node["Name"]], results, total)


def generate_html_report(results, total, expected_total, file_name='report.html'):
    # 样式设计
    styles = """
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            margin: 2rem;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 2rem;
            margin-bottom: 2rem;
        }
        .summary-item {
            padding: 1rem;
            margin: 1rem 0;
            border-left: 4px solid;
        }
        .danger {
            border-color: #dc3545;
            background-color: #f8d7da;
        }
        .success {
            border-color: #28a745;
            background-color: #d4edda;
        }
        .detail-item {
            padding: 1rem;
            margin: 1rem 0;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .path {
            color: #666;
            font-size: 0.9em;
            margin-bottom: 0.5rem;
        }
        .numbers {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-top: 1rem;
        }
        .number-item {
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 4px;
            text-align: center;
        }
        h1, h2 {
            color: #2c3e50;
            margin-top: 0;
        }
        .timestamp {
            color: #666;
            font-size: 0.9em;
        }
    </style>
    """

    # 生成结果卡片
    results_html = ""
    for item in results:
        results_html += f"""
        <div class="detail-item">
            <div class="path">{' → '.join(item['path'])}</div>
            <div class="numbers">
                <div class="number-item">
                    <div>计算值</div>
                    <div style="font-size: 1.2em; color: #dc3545;">{item['calculated']:.2f}</div>
                </div>
                <div class="number-item">
                    <div>实际值</div>
                    <div style="font-size: 1.2em; color: #28a745;">{item['estimate']:.2f}</div>
                </div>
                <div class="number-item">
                    <div>差异值</div>
                    <div style="font-size: 1.2em; color: #ffc107;">{item['difference']:.2f}</div>
                </div>
            </div>
            <div style="margin-top: 1rem;">
                <code>{item['base_price']} × {item['scale']} = {item['calculated']:.2f}</code>
            </div>
        </div>
        """

    # 总体验证结果
    total_match = abs(total['sum'] - expected_total) <= 1
    total_html = f"""
    <div class="numbers">
        <div class="number-item">
            <div>总和计算值</div>
            <div style="font-size: 1.4em; font-weight: bold;">{total['sum']:.2f}</div>
        </div>
        <div class="number-item">
            <div>根节点预期值</div>
            <div style="font-size: 1.4em; font-weight: bold;">{expected_total}</div>
        </div>
        <div class="number-item">
            <div>差异值</div>
            <div style="font-size: 1.4em; font-weight: bold; color: {'#dc3545' if not total_match else '#28a745'}">
                {abs(total['sum'] - expected_total):.2f}
            </div>
        </div>
    </div>
    """

    # 完整HTML结构
    html = f"""
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>数据验证报告</title>
        {styles}
    </head>
    <body>
        <div class="container">
            <h1>数据验证报告 <span class="timestamp">{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</span></h1>

            <div class="card">
                <h2>总览</h2>
                <div class="{'summary-item danger' if len(results) > 0 else 'summary-item success'}">
                    发现 {len(results)} 个不匹配节点
                </div>
                <div class="{'summary-item danger' if not total_match else 'summary-item success'}">
                    总和验证结果: {'不匹配' if not total_match else '匹配'} (差异值: {abs(total['sum'] - expected_total):.2f})
                </div>
            </div>

            <div class="card">
                <h2>节点验证详情</h2>
                {results_html if results else '<div style="color: #28a745;">所有节点验证通过</div>'}
            </div>

            <div class="card">
                <h2>总和验证详情</h2>
                {total_html}
            </div>
        </div>
    </body>
    </html>
    """

    file_name = 'D:\code\\army_project\\testcases\\army\\report.html'
    if os.path.exists(file_name):
        os.remove(file_name)
        print('删除旧文件')
        # 写入文件 新文件
    with open(file_name, 'w', encoding='utf-8') as f:
        f.write(html)
    webbrowser.open(f"file://{os.path.abspath(file_name)}")
